package com.stud.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Description:
 * @Author: sdx
 * @Date: 2022/12/11 21:34
 **/
@Slf4j
@Component
public class RedisDelayQueueUtil {

    @Autowired
    private RedissonClient redissonClient;


    public <T> boolean addElayQueue(T value, long delay, TimeUnit timeUnit, String queueCode) {
        try {
            RBlockingDeque<Object> blockingDeque = redissonClient.getBlockingDeque(queueCode);
            RDelayedQueue<Object> delayedQueue = redissonClient.getDelayedQueue(blockingDeque);
            //检查标识符是否已经存在于队列中
            boolean exists = delayedQueue.contains(value);
            if (!exists) {
                //标识符不存在于队列中,则添加
                delayedQueue.offer(value, delay, timeUnit);
                log.info("(添加延时队列成功) 队列键：{}，队列值：{}，延迟时间：{}", queueCode, value, timeUnit.toSeconds(delay) + "秒");
                return true;
            } else {
                log.info("(标识符已存在于延时队列中) 队列键：{}，标识符：{}", queueCode, value);
                return false;
            }

        } catch (Exception e) {
            log.error("(添加延时队列失败) {}", e.getMessage());
            throw new RuntimeException("(添加延时队列失败)");
        }
    }


    public <T> T getDelayQueue(String queueCode) throws InterruptedException {
        RBlockingDeque<Map> blockingDeque = redissonClient.getBlockingDeque(queueCode);
        //订阅redis队列
        redissonClient.getDelayedQueue(blockingDeque);
        T value = (T) blockingDeque.take();
        return value;
    }
}
